package com.agadmin.manage;

import com.agadmin.config.CustomPasswordEncoder;
import com.agadmin.config.CustomUser;
import com.agadmin.entity.user.Users;
import com.agadmin.mapper.UserMapper;
import com.agadmin.request.login.UserRequest;
import com.agadmin.response.login.RegistryResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;

@Slf4j
@Service
public class UserManager implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    CustomPasswordEncoder encoder;

    public RegistryResponse registry(UserRequest user) {
        RegistryResponse res = new RegistryResponse();
        Users queryUsers = queryUserByName(user.getUserName());
        if (queryUsers != null) {
            res.setMsg("userName exists");
            return res;
        }


        String pwd = encoder.encode(user.getPassword());
        user.setPassword(pwd);

        boolean saveResult = saveUser(user);
        if(saveResult){
            res.setMsg("registry successful");
        }else {
            res.setMsg("registry fail");
        }
        return res;
    }

    private Users queryUserByName(String name) {

        LambdaQueryWrapper<Users> qw = new LambdaQueryWrapper<Users>();
        qw.eq(true, Users::getUserName, name);
        Users users = userMapper.selectOne(qw);
        return users;
    }

    private boolean saveUser(UserRequest req) {
        Users users =new Users();
        BeanUtils.copyProperties(req, users);

        int insert = userMapper.insert(users);

        return insert > 0;
    }

//    自定义登录
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        Users users = queryUserByName(username);
        if(users ==null){
            throw new UsernameNotFoundException("userName or password incorrect");
        }
        log.info("login user id="+users.getId());
       return new CustomUser(users, Collections.emptyList());

    }
}
